#!/usr/bin/env python3
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'enhanced'))

from flask import Flask, render_template_string
import requests
from datetime import datetime

def debug_template_render():
    """调试模板渲染过程"""
    print("=== 调试模板渲染过程 ===")
    print(f"时间: {datetime.now()}")
    
    try:
        # 1. 发送POST请求获取数据
        print("\n1. 发送POST请求...")
        response = requests.post('http://127.0.0.1:5000', data={'coin': 'BTC'})
        
        if response.status_code != 200:
            print(f"请求失败，状态码: {response.status_code}")
            return
        
        # 2. 分析响应中的数据
        html_content = response.text
        print(f"响应大小: {len(html_content)} 字符")
        
        # 3. 查找模板变量的实际值
        print("\n2. 查找已移除指标的数据...")
        
        # 查找包含已移除指标的行
        lines = html_content.split('\n')
        problem_lines = []
        
        removed_indicators = {
            'stochastic k': '22.88',
            'williams %r': '-77.12', 
            'cci': '-48.71',
            'momentum': '98.31'
        }
        
        for i, line in enumerate(lines):
            line_lower = line.lower()
            for indicator, value in removed_indicators.items():
                if indicator in line_lower and value in line:
                    problem_lines.append({
                        'line_num': i + 1,
                        'content': line.strip(),
                        'indicator': indicator,
                        'value': value
                    })
        
        if problem_lines:
            print(f"❌ 发现 {len(problem_lines)} 个包含已移除指标的行")
            
            for item in problem_lines:
                print(f"\n第{item['line_num']}行: {item['content']}")
                print(f"指标: {item['indicator']}, 值: {item['value']}")
        else:
            print("✅ 未发现已移除指标的数据")
        
        # 4. 检查是否有JavaScript变量或内联数据
        print("\n3. 检查JavaScript和内联数据...")
        
        # 查找script标签
        import re
        script_pattern = r'<script[^>]*>(.*?)</script>'
        scripts = re.findall(script_pattern, html_content, re.DOTALL | re.IGNORECASE)
        
        js_problems = []
        for i, script in enumerate(scripts):
            for indicator, value in removed_indicators.items():
                if value in script or indicator.replace(' ', '_') in script.lower():
                    js_problems.append({
                        'script_index': i + 1,
                        'indicator': indicator,
                        'value': value,
                        'content': script[:200] + '...' if len(script) > 200 else script
                    })
        
        if js_problems:
            print(f"❌ JavaScript中发现 {len(js_problems)} 个问题")
            for problem in js_problems:
                print(f"脚本 {problem['script_index']}: {problem['indicator']} = {problem['value']}")
        else:
            print("✅ JavaScript中未发现问题")
        
        # 5. 检查模板中的硬编码HTML
        print("\n4. 检查硬编码HTML...")
        
        # 查找包含这些特定数值的HTML标签
        html_problems = []
        for indicator, value in removed_indicators.items():
            # 使用更精确的正则表达式查找
            value_pattern = rf'<[^>]*>\s*{re.escape(value)}\s*</[^>]*>'
            matches = re.findall(value_pattern, html_content)
            
            if matches:
                html_problems.extend([
                    {
                        'indicator': indicator,
                        'value': value,
                        'match': match
                    } for match in matches
                ])
        
        if html_problems:
            print(f"❌ HTML中发现 {len(html_problems)} 个硬编码问题")
            for problem in html_problems:
                print(f"{problem['indicator']} = {problem['value']}: {problem['match']}")
        else:
            print("✅ HTML中未发现硬编码问题")
        
        # 6. 尝试找到数据来源
        print("\n5. 分析数据来源...")
        
        # 检查是否有模板缓存
        print("检查可能的数据来源:")
        print("  1. 模板文件中的硬编码数据")
        print("  2. Flask模板缓存")
        print("  3. 服务器端的默认/测试数据")
        print("  4. 浏览器缓存")
        
        # 7. 提供解决方案
        print("\n6. 建议的解决步骤:")
        print("  1. 检查templates/index.html是否有未保存的更改")
        print("  2. 重启Flask应用程序")
        print("  3. 清除浏览器缓存")
        print("  4. 检查是否有其他模板文件")
        print("  5. 检查enhanced/technical_analysis.py中的默认值")
        
    except Exception as e:
        print(f"调试过程中出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    debug_template_render()